package com.chonglie;

import java.io.StringWriter;
import java.util.List;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import org.xmlpull.v1.XmlSerializer;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.util.Xml;
import android.view.View;
import android.widget.EditText;

import com.chonglie.tools.SAXHandler;

public class ParserXmlActivity extends Activity {

	SAXHandler handler;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.parser_xml);
	}

	public void loadXml(View view) {
		if (handler != null) {
			return;
		}

		SAXParserFactory factory = SAXParserFactory.newInstance();

		try {
			SAXParser parser = factory.newSAXParser();
			XMLReader reader = parser.getXMLReader();
			handler = new SAXHandler();
			reader.setContentHandler(handler);
			reader.parse(new InputSource(this.getResources().openRawResource(
					R.raw.books)));

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void writeXml(View view) {
		if (handler == null) {
			return;
		}

		EditText memo = (EditText) findViewById(R.id.parser_text);

		XmlSerializer serializer = Xml.newSerializer();
		StringWriter writer = new StringWriter();

		try {
			serializer.setOutput(writer);
			serializer.startDocument("UTF-8", true);

			List<String> keys = handler.getKeys();
			List<Object> values = handler.getValues();

			String key;
			Object value;
			String[] attr;
			for (int i = 0; i < keys.size(); i++) {
				key = keys.get(i);
				value = values.get(i);
				if (SAXHandler.TAG_START.equals(key)) {
					serializer.startTag("", value.toString());
				} else if (SAXHandler.TAG_ATTR.equals(key)) {
					attr = (String[]) value;
					serializer.attribute("", attr[0], attr[1]);
				} else if (SAXHandler.TAG_TEXT.equals(key)) {
					serializer.text(value.toString());
				} else if (SAXHandler.TAG_END.equals(key)) {
					serializer.endTag("", value.toString());
				}

				Log.e(key, value.toString());
			}

			serializer.endDocument();
			String text = writer.toString();
			text = text.replaceAll("><", ">\r\n<");
			memo.setText(text);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
